package com.ztman.rxjava.model.entityExtends.weather;

import com.ztman.rxjava.model.baseEntity.BaseResponser;
import com.ztman.rxjava.server.retrofit.OnNetRequestListener;
import com.ztman.rxjava.server.retrofit.RetrofitService;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by YJH on 2017/11/29.
 * 功能：网络请求
 * 天气信息的数据请求和数据类型的转换并输出
 */

public class WeatherModelIml implements WeatherModel{
    @Override
    public void setWeatherParams(String area, String needMoreDay,
                                 String needIndex, String needAlarm,
                                 String need3HourForcast,
                                 final OnNetRequestListener<BaseResponser<ShowApiWeather>> listener) {

        Observable<BaseResponser<ShowApiWeather>> observable = RetrofitService.getInstance().
                createWeatherApi().getWeather(RetrofitService.getInstance().getCacheControl(),
                area, needMoreDay, needIndex, needAlarm, need3HourForcast);

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        listener.onRequestStart();
                    }
                }).subscribe(new Subscriber<BaseResponser<ShowApiWeather>>() {
            @Override
            public void onCompleted() {
                listener.onRequestFinish();
            }

            @Override
            public void onError(Throwable e) {
                listener.onRequestFailure(e);
                listener.onRequestFinish();
            }

            @Override
            public void onNext(BaseResponser<ShowApiWeather> weather) {
                //成功获取到数据并转换类型输出
                listener.onRequestSuccess(weather);
            }
        });
    }
}
